package com.example.demo.leetcode.top100;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _29删除链表的倒数第N个结点
 * @description
 * @date 2023/06/11 10:46
 * <p>
 * ******************************************************
 */
public class _29删除链表的倒数第N个结点 {
    ListNode pre = null;

    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        reverse(dummy, n);
        if (pre != null && pre.next !=null) {
            pre.next = pre.next.next;
        }
        return dummy.next;
    }

    private int reverse(ListNode dummy, int n) {
        if (dummy == null) {
            return 0;
        }
        int i = reverse(dummy.next, n);
        if (n == i) {
            // 找到第n个
            pre = dummy;
        }
        return i + 1;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
